package lacus.wd_cinema.service;

import lacus.wd_cinema.entity.LogRecord;
import lacus.wd_cinema.entity.User;
import lacus.wd_cinema.repository.LogRecordRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 业务日志业务处理类
 * @author lacus
 * @version 0.5
 * @since 0.5
 */
@Service
@Transactional
public class LogService {
    private final LogRecordRepository logRecordRepository;

    public LogService(LogRecordRepository logRecordRepository) {
        this.logRecordRepository = logRecordRepository;
    }

    /** 记录业务日志 */
    public void log(User operator, String operation) {
        LogRecord logRecord = new LogRecord();
        LocalDateTime now = LocalDateTime.now();
        logRecord.setTimestamp(now);
        logRecord.setRole(operator.getRole());
        logRecord.setMessage("[%s]操作人：(ID=%d) 操作：'%s' %s".formatted(
                now, operator.getId(), operator.getUsername(), operation));
        logRecordRepository.save(logRecord);
    }

    /** 获取管理员操作日志 */
    public List<LogRecord> getAdminLog() {
        return logRecordRepository.findAllByRole(User.Role.ROLE_ADMIN);
    }

    /** 获取经理操作日志 */
    public List<LogRecord> getManagerLog() {
        return logRecordRepository.findAllByRole(User.Role.ROLE_MANAGER);
    }
}
